package api

import (
	"github.com/gin-gonic/gin"
	"monthly-test/global"
	"monthly-test/internal/model/dao"
	"monthly-test/internal/model/service"
	"monthly-test/internal/pkg"
	"monthly-test/internal/request"
	"net/http"
)

func Login(c *gin.Context) {

	var req request.LoginReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
		return
	}
	account, err := service.CheckUserByAccount(req.Account)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "账号不存在"})
		return
	}
	if global.Rdb.Get("count").Val() >= "3" {
		c.JSON(http.StatusBadRequest, gin.H{"message": "账号已被锁定"})
		return
	}
	if account.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "密码错误"})
		global.Rdb.Incr("count").Val()
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "登录成功"})

}

func Register(c *gin.Context) {
	account := c.PostForm("account")
	password := c.PostForm("password")
	user := dao.User{
		Account:  account,
		Password: pkg.Md5(password),
	}
	err := global.DB.Create(&user).Error
	if err != nil {
		return
	}
}

func Update(c *gin.Context) {
	var req request.UpdateReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
		return
	}
	err = service.UpdateUser(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "修改失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": "200", "message": "修改成功"})

}
